'use strict';
import {
  Alert,
  Platform,
} from 'react-native'
import Constant from './Constant'
const HOST = Constant.HOST
export function request(url, method, body) {
  var isOk;
  let ContentType = 'application/json'
  let str = "";
  let extraParam = {
    method: method ? method.toUpperCase() : 'GET',
    headers: {
      'Cache-Control': 'no-cache',
      'Content-Type': ContentType
    }
  }
  if ((Platform.OS.toLowerCase() === "android" && method.toUpperCase() == "POST") || Platform.OS.toLowerCase() === "ios") {
    //android get方法不需要body参数
    extraParam['body'] = body;
  } else {
    //android get方法下
    body = (function (obj) {

      for (var prop in obj) {
        str += prop + "=" + obj[prop] + "&"
      }
      return str;
    })(body);
    url = url + '?' + str
  }
  console.log(HOST + url, )

  return new Promise((resolve, reject) => {
    fetch(HOST + url, extraParam)
      .then((response) => {
        if (response.ok) {
          isOk = true;
        } else {
          isOk = false;
        }
        return response.json();
      })
      .then((responseData) => {
        if (isOk) {
          console.log(responseData);
          resolve(responseData);
        } else {
          console.log(responseData);
          reject(responseData);
        }
      })
      .catch((error) => {
        reject(error);
      });
  })
}

/**
 * 用odata抓取远端API的结构
 * @param  {String} api    api 根地址
 * @param  {String} path   请求路径
 * @param  {Objece} params 参数
 * @return {Promise}       包含抓取任务的Promise
 */
export function fetchOdata(api, path, params, header, method, RecId, token) {
  //'Accept': 'application/json'
  api = api ? api : HOST + '/bods.svc';
  path = path ? path : '';
  RecId = RecId ? "(\'" + RecId + "\')" : ''
  let isOk;
  var object = {};
  console.log(header)
  return new Promise((resolve, reject) => {
    fetch(`${api}/${path}${RecId}` + '?token=' + token, {
      method: method ? method : 'GET',
      headers: header ? header : { 'Content-Type': 'application/json', 'Accept': 'application/json' },
      body: JSON.stringify(Object.assign(object, params))
    }).then((response) => {
      if (response.ok) {
        isOk = true;
      } else {
        isOk = false;
      }
      return response.json();
    })
      .then((responseData) => {
        if (isOk) {
          resolve(responseData);
        } else {
          reject(responseData);
        }
      })
      .catch((error) => {
        reject(error);
      });
  })
}

